/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.pathfinder.wizards;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import org.openide.DialogDescriptor;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.WizardDescriptor;
import org.openide.util.Lookup;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import pt.iasd.youthshelter.datamodel.PathfinderRole;
import pt.iasd.youthshelter.datamodel.Role;
import pt.iasd.youthshelter.datamodel.service.PathfinderRoleController;

/**
 *
 * @author Rui
 */
public class PathfinderRoleTablePanel extends javax.swing.JPanel {
    private static final ResourceBundle bundle = java.util.ResourceBundle.getBundle("pt/iasd/youthshelter/pathfinder/Bundle");
    
    /* Logging object. */
    private Logger logger = Logger.getLogger(this.getClass().getName());
    
    private List<PathfinderRole> pathfinderRoles = loadPathfinderRoleTableData();
    
    private Set<Integer> editedPathfinderRoles = new HashSet<Integer>();
    
    private Set<Integer> removedPathfinderRoles = new HashSet<Integer>();

    /**
     * Creates new form PathfinderRoleTablePanel
     */
    public PathfinderRoleTablePanel() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        AddButton = new javax.swing.JButton();
        EditButton = new javax.swing.JButton();
        RemoveButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        PathfinderRoleTable = new javax.swing.JTable();

        setPreferredSize(new java.awt.Dimension(700, 300));

        org.openide.awt.Mnemonics.setLocalizedText(AddButton, bundle.getString("Buttons.Add"));
        AddButton.setMaximumSize(new java.awt.Dimension(100, 23));
        AddButton.setMinimumSize(new java.awt.Dimension(100, 23));
        AddButton.setPreferredSize(new java.awt.Dimension(100, 23));
        AddButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(EditButton, bundle.getString("Buttons.Edit"));
        EditButton.setMaximumSize(new java.awt.Dimension(100, 23));
        EditButton.setMinimumSize(new java.awt.Dimension(100, 23));
        EditButton.setPreferredSize(new java.awt.Dimension(100, 23));
        EditButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                EditButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(RemoveButton, bundle.getString("Buttons.Remove"));
        RemoveButton.setMaximumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setMinimumSize(new java.awt.Dimension(100, 23));
        RemoveButton.setPreferredSize(new java.awt.Dimension(100, 23));
        RemoveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveButtonActionPerformed(evt);
            }
        });

        PathfinderRoleTable.setModel(buildTableModel());
        PathfinderRoleTable.removeColumn(PathfinderRoleTable.getColumn(PathfinderRoleTable.getColumnName(0)));
        EditButton.setEnabled(false);
        RemoveButton.setEnabled(false);
        PathfinderRoleTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                PathfinderRoleTableMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(PathfinderRoleTable);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 584, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(AddButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(EditButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(RemoveButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(AddButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(EditButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(RemoveButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(208, Short.MAX_VALUE))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void AddButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddButtonActionPerformed
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<WizardDescriptor.Panel<WizardDescriptor>>();
        panels.add(new AddPathfinderRoleWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<WizardDescriptor>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("PathfinderRole.Title.Add"));
        wiz.putProperty(WizardKeys.PROP_LIST, pathfinderRoles);
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            Pathfinder pathfinder = (Pathfinder)wiz.getProperty(WizardKeys.PROP_PATHFINDER);
            Role role = (Role)wiz.getProperty(WizardKeys.PROP_ROLE);
            String place = (String)wiz.getProperty(WizardKeys.PROP_PLACE);
            Date startDate = (Date)wiz.getProperty(WizardKeys.PROP_START_DATE);
            Date endDate = (Date)wiz.getProperty(WizardKeys.PROP_END_DATE);
            pathfinderRoles.add(new PathfinderRole(startDate, endDate, place, role, pathfinder));
            setTable();
        }
    }//GEN-LAST:event_AddButtonActionPerformed

    private void EditButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_EditButtonActionPerformed
        int selectedRow = PathfinderRoleTable.getSelectedRow();
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<WizardDescriptor.Panel<WizardDescriptor>>();
        panels.add(new EditPathfinderRoleWizardPanel());
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<WizardDescriptor>(panels));
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle(bundle.getString("PathfinderRole.Title.Edit"));
        PathfinderRole pathfinderRole = pathfinderRoles.get(selectedRow);
        wiz.putProperty(WizardKeys.PROP_LIST, pathfinderRoles);
        wiz.putProperty(WizardKeys.PROP_ID, pathfinderRole.getId());
        wiz.putProperty(WizardKeys.PROP_PATHFINDER, pathfinderRole.getPathfinderId());
        wiz.putProperty(WizardKeys.PROP_ROLE, pathfinderRole.getRoleId());
        wiz.putProperty(WizardKeys.PROP_PLACE, pathfinderRole.getPlace());
        wiz.putProperty(WizardKeys.PROP_START_DATE, pathfinderRole.getStartDate());
        wiz.putProperty(WizardKeys.PROP_END_DATE, pathfinderRole.getEndDate());
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            pathfinderRole.setPathfinderId((Pathfinder)wiz.getProperty(WizardKeys.PROP_PATHFINDER));
            pathfinderRole.setRoleId((Role)wiz.getProperty(WizardKeys.PROP_ROLE));
            pathfinderRole.setPlace((String)wiz.getProperty(WizardKeys.PROP_PLACE));
            pathfinderRole.setStartDate((Date)wiz.getProperty(WizardKeys.PROP_START_DATE));
            pathfinderRole.setEndDate((Date)wiz.getProperty(WizardKeys.PROP_END_DATE));
            if(pathfinderRole.getId() != null) {
                editedPathfinderRoles.add(pathfinderRole.getId());
            }
            setTable();
        }
    }//GEN-LAST:event_EditButtonActionPerformed

    private void RemoveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveButtonActionPerformed
        int selectedRow = PathfinderRoleTable.getSelectedRow();
        NotifyDescriptor dialog = new NotifyDescriptor(
                String.format(bundle.getString("PathfinderRole.Confirmation.Remove"),
                        pathfinderRoles.get(selectedRow).getRoleId().getName(),
                        pathfinderRoles.get(selectedRow).getPathfinderId().getName()),
                bundle.getString("PathfinderRole.Title.Remove"), NotifyDescriptor.OK_CANCEL_OPTION,
                NotifyDescriptor.WARNING_MESSAGE, null, null);
        if(DialogDisplayer.getDefault().notify(dialog) == DialogDescriptor.OK_OPTION) {
            if(pathfinderRoles.get(selectedRow).getId() != null) {
                removedPathfinderRoles.add(pathfinderRoles.get(selectedRow).getId());
            }
            pathfinderRoles.remove(selectedRow);
            setTable();
        }
    }//GEN-LAST:event_RemoveButtonActionPerformed

    private void PathfinderRoleTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_PathfinderRoleTableMousePressed
        int selectedRow = PathfinderRoleTable.getSelectedRow();
        if(selectedRow != -1) {
            EditButton.setEnabled(true);
            RemoveButton.setEnabled(true);
        } else {
            EditButton.setEnabled(false);
            RemoveButton.setEnabled(false);
        }
    }//GEN-LAST:event_PathfinderRoleTableMousePressed

    public List<PathfinderRole> getPathfinderRoles() {
        return pathfinderRoles;
    }

    public Set<Integer> getEditedPathfinderRoles() {
        return editedPathfinderRoles;
    }

    public Set<Integer> getRemovedPathfinderRoles() {
        return removedPathfinderRoles;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton AddButton;
    private javax.swing.JButton EditButton;
    private javax.swing.JTable PathfinderRoleTable;
    private javax.swing.JButton RemoveButton;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    // <editor-fold defaultstate="collapsed" desc="Table Data Code">
    private List<PathfinderRole> loadPathfinderRoleTableData() {
        PathfinderRoleController controller = Lookup.getDefault().lookup(PathfinderRoleController.class);
        if(controller != null) {
            try{
                return controller.findPathfinderRoleEntities();
            } catch(Exception ex) {
                logger.log(Level.SEVERE, ex.getLocalizedMessage(), ex);
            }
        }
        return null;
    }
    
    private DefaultTableModel buildTableModel(){
        Object[][] data;
        String[] headers = new String[]{
            bundle.getString("TableHeaders.Id"),
            bundle.getString("TableHeaders.Pathfinder"),
            bundle.getString("TableHeaders.Role"),
            bundle.getString("TableHeaders.Place"),
            bundle.getString("TableHeaders.Date.Start"),
            bundle.getString("TableHeaders.Date.End")};
        if(pathfinderRoles == null || pathfinderRoles.isEmpty()) {
            data = new Object[][]{};
        } else {
            data = new Object[pathfinderRoles.size()][PathfinderRole.class.getDeclaredFields().length - 1];
            int i = 0;
            for(PathfinderRole pathfinderRole : pathfinderRoles) {
                data[i][0] = pathfinderRole.getId();
                data[i][1] = pathfinderRole.getPathfinderId().getName();
                data[i][2] = pathfinderRole.getRoleId().getName();
                data[i][3] = pathfinderRole.getPlace();
                data[i][4] = pathfinderRole.getStartDate();
                data[i][5] = pathfinderRole.getEndDate();
                ++i;
            }
        }
        DefaultTableModel tablemodel = new DefaultTableModel(data, headers){
            Class[] types = new Class[]{java.lang.Integer.class, java.lang.String.class, java.lang.String.class,
                java.lang.String.class, java.util.Date.class, java.util.Date.class};
            boolean[] canEdit = new boolean[]{false, false, false, false, false, false};

            @Override
            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        };
        return tablemodel;
    }
    
    private void setTable() {
        PathfinderRoleTable.setModel(buildTableModel());
        PathfinderRoleTable.removeColumn(PathfinderRoleTable.getColumn(PathfinderRoleTable.getColumnName(0)));
        EditButton.setEnabled(false);
        RemoveButton.setEnabled(false);
    }// </editor-fold>
}
